//
//  UIWindow+XG.m
//  YiCuiMiaoZhang
//
//  Created by Sings on 2019/3/29.
//  Copyright © 2018 益萃网络科技（中国）有限公司. All rights reserved.
//

#import "UIWindow+BZ.h"

@implementation UIWindow (BZ)

- (BZBaseViewController *)windowsLastViewController {

    UIWindow *topWindow = [UIApplication sharedApplication].keyWindow;
    if (topWindow.windowLevel != UIWindowLevelNormal) {
        topWindow = [self returnWindowWithWindowLevelNormal];
    }

    UIViewController *topController = topWindow.rootViewController;
    if (topController == nil) {
        topWindow = [UIApplication sharedApplication].delegate.window;
        if (topWindow.windowLevel != UIWindowLevelNormal) {
            topWindow = [self returnWindowWithWindowLevelNormal];
        }
        topController = topWindow.rootViewController;
    }

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    if ([topController isKindOfClass:[UITabBarController class]]) {
        int index = [(UITabBarController *)topController selectedIndex];
        UINavigationController *nav =
            [((UITabBarController *)topController).viewControllers objectAtIndex:index];
        topController = [nav.viewControllers lastObject];

        while (topController.presentedViewController) {
            topController = topController.presentedViewController;
        }
    }

    if ([topController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)topController;
        topController               = [nav.viewControllers lastObject];

        while (topController.presentedViewController) {
            topController = topController.presentedViewController;
        }
    }

    return (BZBaseViewController *)topController;
}

- (UIWindow *)returnWindowWithWindowLevelNormal {
    NSArray *windows = [UIApplication sharedApplication].windows;
    for (UIWindow *topWindow in windows) {
        if (topWindow.windowLevel == UIWindowLevelNormal) return topWindow;
    }
    return [UIApplication sharedApplication].keyWindow;
}

@end
